GetIRFPicdata <- function(irf, cum = T, n =24){
  irf_bench <- list()
  irf_imp <- list()
  k <- 1
  for (i in 1:length(irf)) {
    for (j in 1:length(irf[[1]])) {
      irf_bench[[k]] <- irf[[i]][[j]]$benchvar_bench
      irf_imp[[k]] <- irf[[i]][[j]]$benchvar_imp
      k <- k + 1
    }
  }
  irf_bench <- bind_rows(irf_bench)
  irf_imp <- bind_rows(irf_imp)
  irfdelta <- irf_bench
  irfdelta[,-c(1:2,7)] <- irf_imp[,-c(1:2,7)] - irf_bench[,-c(1:2,7)]
  irfdelta <- dplyr::group_by(irfdelta[!is.na(irfdelta$cpi),],cnt,n) %>%
    dplyr::summarise(cpiAve = quantile(cpi,0.5), gdpAve = quantile(gdp,0.5),
              TFPAve = quantile(TFP,0.5), unctnAve = quantile(unctn, 0.5,na.rm = T),
              cpi025 = quantile(cpi,0.05), gdp025 = quantile(gdp,0.05),
              TFP025 = quantile(TFP,0.05), unctn025 = quantile(unctn,0.05,na.rm = T),
              cpi975 = quantile(cpi,0.95), gdp975 = quantile(gdp,0.95),
              TFP975 = quantile(TFP,0.95), unctn975 = quantile(unctn,0.95,na.rm = T))
  # 累积脉冲？
  if (cum){
    for (cnt in unique(irfdelta$cnt)) {
      for (var in c('cpi','gdp','TFP','unctn')) {
        for (suf in c('Ave','025','975')) {
          exetxt <- paste('irfdelta$',var,suf,
                          '[irfdelta$cnt %in% cnt] <- cumsum(irfdelta$',
                          var,suf,'[irfdelta$cnt %in% cnt])',sep = '')
          eval(parse(text = exetxt))
        }
      }
    }
  }
  return(irfdelta[irfdelta$n <= n,])
}

DrawIRF <- function(dn, up, responseCnt = 'CHN',resvar = 'TFP'){
  rcode <- paste("p <- ggplot(dn[dn$cnt %in% responseCnt,], aes(x = n, y =", resvar,"Ave)) +
    geom_line(color = I('red')) +
    geom_line(data = up[up$cnt %in% responseCnt,], aes(x = n, y =", resvar,"Ave)) +
    geom_hline(yintercept = 0, color = I('red')) + geom_point() +
    theme_bw() +
    scale_x_continuous(breaks = seq(1,max(dn$n),2))",sep = '')
  eval(parse(text = rcode))
  return(p + labs(x = '时期', y = '脉冲响应'))
}
